//
//  composeMessageViewController.m
//  TTAddressBook
//
//  Created by 贾政阳 on 12-1-10.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "composeMessageViewController.h"
#import "selectContacts.h"
#import "AppDelegate.h"
#define BUTTON_TAG_BASE 100
@interface composeMessageViewController() 

-(void)sendMessage;
-(void)addReceptionView;
-(void)addOneReception;
-(void)addReceiver;
-(void)resumeView;
-(void)deleteButton:(id)sender;
-(void)delayPopView;
-(void)delayPopToRootView;
@end

@implementation composeMessageViewController
@synthesize receptionArray, allContactDic,smsText,subSend,isSendBack,sendBackDic,isSelectContacts2sms;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle
-(void)textchange:(NSNotification*)note{
    if([receptionTextFiled.text length] == 0)
    {
        receptionTextFiled.text = @" ";
    }

}

-(void)addNotification{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(textchange:)
                                                 name:UITextFieldTextDidChangeNotification
                                               object:nil];
}

-(id)initWithContact:(NSDictionary*)allContact withRecepion:(NSMutableArray*)reception{
    
    if (self = [super init]){
        
        [self addNotification];
        
        if (allContactDic != nil) {
            self.allContactDic = allContactDic;
        }else{
            //self.allContactDic = [[ModelEngine getInstance] listAllContacts];
        }
        
        if (reception != nil) {
            self.receptionArray = reception;
        }else{
            self.receptionArray = [[[NSMutableArray alloc] init] autorelease];
        }
    }
    return self;
}
-(id)initWithContact:(NSMutableArray*)reception{
    
    if (self = [super init]){
        isSendBack = NO;
        self.hidesBottomBarWhenPushed = YES;
        [self addNotification];
        self.receptionArray = [[[NSMutableArray alloc] init] autorelease];
        [self.receptionArray addObjectsFromArray:reception];
        person2Send = YES;

    }
    return self;
}

-(id)init{
    
    if (self = [super init]) {

        [self addNotification];
        
       // self.allContactDic = [[ModelEngine getInstance] listAllContacts];
        self.receptionArray = [[[NSMutableArray alloc] init] autorelease];
        [MyClass getInstance].personMarkList=nil;
        
    }
    return self;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillHideNotification 
                                                  object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                    name:UIKeyboardWillShowNotification
                                                  object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UITextFieldTextDidChangeNotification
                                                  object:nil];
    
    [self.receptionArray removeAllObjects];
    self.receptionArray = nil;
    self.sendBackDic = nil;
    self.allContactDic = nil;
    [popTipView release];
    [textView release];
    [containerView release];
    [receptionView release];
    [receptionTextFiled release];
    [super dealloc];
}
-(void)back{
    if (([receptionArray count] > 1)&&(!isSelectContacts2sms)) {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
    else
        [self.navigationController popViewControllerAnimated:YES];
}
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
    
    UIView* selfView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame];
    self.view = selfView;
    [selfView release];
    
    self.navigationController.title = @"新信息";
    
    UIView* backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 43, 320, 480)];
    backgroundView.backgroundColor = [UIColor colorWithRed:219/255.0f green:226/255.0f blue:237/255.0f alpha:1.0f];
    [self.view addSubview:backgroundView];
    [backgroundView release];
    
    //内容输入框
    CGRect frame = CGRectMake(0, self.view.frame.size.height - 40, 320, 40);
    containerView = [[UIView alloc] initWithFrame:frame]; 
    textView = [[HPGrowingTextView alloc] initWithFrame:CGRectMake(1, 2, 250, 40)];
    textView.contentInset = UIEdgeInsetsMake(0, 5, 0, 5);
    textView.backgroundColor = [UIColor clearColor];
    textView.minNumberOfLines = 1;
    textView.maxNumberOfLines = 5;
    textView.returnKeyType = UIReturnKeyDefault;
    textView.font = [UIFont systemFontOfSize:15.0f];
    textView.delegate = self;
    textView.internalTextView.scrollIndicatorInsets = UIEdgeInsetsMake(5, 0, 5, 0);
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleBordered target:self action:@selector(back)] autorelease];
    [self.view addSubview:containerView];
    
    UIImage *rawEntryBackground = [UIImage imageNamed:@"MessageEntryInputField.png"];
    UIImage *entryBackground = [rawEntryBackground stretchableImageWithLeftCapWidth:13 topCapHeight:22];
    UIImageView *entryImageView = [[[UIImageView alloc] initWithImage:entryBackground] autorelease];
    entryImageView.frame = CGRectMake(5, 0, 248, 40);
    entryImageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    
    UIImage *rawBackground = [UIImage imageNamed:@"MessageEntryBackground.png"];
    UIImage *background = [rawBackground stretchableImageWithLeftCapWidth:13 topCapHeight:22];
    UIImageView *imageView = [[[UIImageView alloc] initWithImage:background] autorelease];
    imageView.frame = CGRectMake(0, 0, containerView.frame.size.width, containerView.frame.size.height);
    imageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    
    textView.autoresizingMask = UIViewAutoresizingFlexibleWidth;

    [containerView addSubview:imageView];
    [containerView addSubview:textView];
    [containerView addSubview:entryImageView];
    
    UIImage *sendBtnBackground = [[UIImage imageNamed:@"MessageEntrySendButton.png"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];
    UIImage *selectedSendBtnBackgroun = [[UIImage imageNamed:@"MessageEntrySendButton.png"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];
    UIButton *sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    sendBtn.backgroundColor = [UIColor clearColor];
    sendBtn.frame = CGRectMake(containerView.frame.size.width-69,  8, 63, 27);
    sendBtn.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin;
    [sendBtn setTitle:@"发送" forState:UIControlStateNormal];
    
    [sendBtn setTitleShadowColor:[UIColor colorWithWhite:0 alpha:0.4] forState:UIControlStateNormal];
    [sendBtn addTarget:self action:@selector(sendMessage) forControlEvents:UIControlEventTouchUpInside];
    [sendBtn setBackgroundImage:sendBtnBackground forState:UIControlStateNormal];
    [sendBtn setBackgroundImage:selectedSendBtnBackgroun forState:UIControlStateSelected];
    [containerView addSubview:sendBtn];

    containerView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    
    //收件人输入
    receptionView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 43)];
    [self.view addSubview:receptionView];
    receptionView.backgroundColor = [UIColor whiteColor];
    UILabel* receptionLable = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 72, 43)];
    receptionLable.font = [UIFont systemFontOfSize:16.0f];
    receptionLable.text = @"收件人：";
    receptionLable.textColor = [UIColor grayColor];
    receptionLable.textAlignment = UITextAlignmentCenter;
    [receptionView addSubview:receptionLable];
    [receptionLable release];
    
    receptionTextFiled = [[UITextField alloc] initWithFrame:CGRectMake(76, 0, 230, 43)];
    receptionTextFiled.font = [UIFont systemFontOfSize:14.0f];
    receptionTextFiled.backgroundColor = [UIColor clearColor];
    receptionTextFiled.adjustsFontSizeToFitWidth = YES;
    receptionTextFiled.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    receptionTextFiled.delegate = self;
    [receptionView addSubview:receptionTextFiled];
    
    UIButton* addButton = [[UIButton buttonWithType:UIButtonTypeContactAdd] retain];
    addButton.backgroundColor = [UIColor clearColor];
    addButton.frame = CGRectMake(280, 0, 24, 24);
	addButton.tag = 99;
	[receptionView addSubview:addButton];
    [addButton addTarget:self action:@selector(addReceptionView) forControlEvents:UIControlEventTouchUpInside]; 
    [addButton release];
    if (person2Send) {
        //addButton.hidden = YES;
    }
    if ([self.smsText length]>0) {
        textView.text = self.smsText;
        containerView.frame = CGRectMake(0, self.view.frame.size.height - 40, 320, 80); 
        textView.frame=CGRectMake(1, 2, 250, 80);
        entryImageView.frame = CGRectMake(5, 0, 248, 80);
        imageView.frame = CGRectMake(0, 0, containerView.frame.size.width, containerView.frame.size.height);
    }
    
    popTipView = [[UIView alloc] initWithFrame:CGRectMake(90, 60, 140, 40)];
    popTipView.layer.cornerRadius = 6;
    popTipView.layer.masksToBounds = YES;
    popTipView.backgroundColor = [UIColor blackColor];
    popTipView .alpha = 0.0f;
    
    UILabel* popLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 140, 40)];
    popLabel.tag = 20;
    popLabel.textAlignment = UITextAlignmentCenter;
    popLabel.backgroundColor = [UIColor blackColor];
    popLabel.font = [UIFont systemFontOfSize:14.0];
    popLabel.textColor = [UIColor whiteColor];
    popLabel.text = @"发送失败";
    [popTipView addSubview:popLabel];
    [popLabel release];
    
    [self.view addSubview:popTipView];
    
    [receptionTextFiled becomeFirstResponder];
}

-(void)popSendMsgRetView:(int)code {
    UILabel* contentLabel = (UILabel*)[popTipView viewWithTag:20];
    if (code == 0) {
        contentLabel.text = @"发送成功";
    }
    else{
        contentLabel.text = @"发送失败";
    }
    popTipView.frame = CGRectMake(90, containerView.frame.origin.y -50, 140, 40);
    popTipView.alpha = 0.8f;    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration: 1.5];
    
    popTipView.alpha = 0.0f;
    
    [UIView commitAnimations];
}

#pragma mark viewWillAppear 显示前加载全部的联系人
- (void) viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    //获取所有的联系人信息
    
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark button selector
-(void)addOneReception
{
    //添加联系人的信息  AddressBookContactSearchResult
    NSString* temp = [receptionTextFiled.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    receptionTextFiled.text= @" ";
    return;
    if (temp.length == 0) {
        return;
    }else{        
        [receptionArray addObject:temp];
    }
    receptionTextFiled.text = @" ";
}
-(void)sendMessage{
    NSMutableArray * arrContacts;
    arrContacts = [[NSMutableArray alloc] init];
    for (NSDictionary* dict in receptionArray) {
        NSString *Mark = [dict objectForKey:@"personMark"];
        [arrContacts addObject:Mark];
    }
    if (arrContacts) {
        NSString *str = textView.text;
        if ([arrContacts count]>0)
        {
            /*
             UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
             
             UIView* sendView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
             sendView.backgroundColor = [UIColor whiteColor];
             sendView.alpha = 0.1;
             [tempWindow addSubview:sendView];
             [sendView release];
             
             UIView* centerView = [[UIView alloc] initWithFrame:CGRectMake(110, 190, 100, 100)];
             centerView.layer.cornerRadius = 6;
             centerView.layer.masksToBounds = YES;
             centerView.backgroundColor = [UIColor blackColor];
             centerView.alpha = 0.8;
             [tempWindow addSubview:centerView];
             
             UIActivityIndicatorView *aiv = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
             aiv.center = CGPointMake(50, 50);
             [aiv startAnimating];
             
             [centerView addSubview:aiv];
             [aiv release];
             
             [centerView release];
            */
            [theAppDelegate showActivityView:YES text:@"正在发送信息..."];
            NSDictionary* retDic = [[MyClass getInstance] sendMessage:str _to:arrContacts];
            int code = [(NSNumber*)[retDic objectForKey:@"code"] intValue];
            textView.text=@"";

            if ( ([arrContacts count]==1) && (code==0)) //一个联系人 且发送成功后跳到详情页面
            {
                if (isSendBack) {
                    NSString *Mark = [self.sendBackDic objectForKey:@"personMark"];
                    NSDictionary* onedic = (NSDictionary*)[receptionArray objectAtIndex:0];
                    NSString *oneMark = [onedic objectForKey:@"personMark"];
                    if ([Mark isEqualToString:oneMark]) 
                    {
                        [theAppDelegate showActivityView:NO text:nil];
                        [self.navigationController popViewControllerAnimated:YES];
                    }
                    [theAppDelegate showActivityView:NO text:nil];
                    [self.navigationController popToRootViewControllerAnimated:YES];
                }
                else
                {
                    [theAppDelegate showActivityView:NO text:nil];
                    NSDictionary* onedic = (NSDictionary*)[receptionArray objectAtIndex:0];
                    detailMessageViewController *view = [[detailMessageViewController alloc] initWithOneContact:onedic];
                    [self.navigationController pushViewController:view animated:YES];
                    [view release];
                }
            }            
            else
            {
                [self popSendMsgRetView:code];
                //if (isSendBack) 
                {
                    if (code == 0) {
                        [theAppDelegate showActivityView:NO text:nil];
                        [self performSelector:@selector(delayPopToRootView) withObject:nil afterDelay:1.5f];
                        //[self.navigationController popToRootViewControllerAnimated:YES];
                    }
                }
            }
            [MyClass getInstance].personMarkList = nil;
            self.receptionArray=nil;
            [self resumeView];
            [theAppDelegate showActivityView:NO text:nil];
        }
    }
    [arrContacts release];
}

-(void)addReceptionView{
//    if (person2Send) {
//        if ([receptionArray count]>1)
//            [self.navigationController popViewControllerAnimated:YES];
//    }
    selectContacts* view;
    if ([receptionArray count]>0) {
        view = [[selectContacts alloc] initWithMessageContacts:receptionArray];
    }
    else
        view = [[selectContacts alloc] initWithContacts:nil];
    [self.navigationController pushViewController:view animated:YES];
    [view release];
}

-(void)addReceiver
{
	[self resumeView];
	
	int receptionWidth = 62;
    int receptionHeight = 10;
    CGSize size;
    if ([MyClass getInstance].personMarkList) {
        if (receptionArray) {
            [receptionArray removeAllObjects];
        }
        else
        {
           self.receptionArray =  [[NSMutableArray alloc] init];
        }
        [self.receptionArray addObjectsFromArray:[MyClass getInstance].personMarkList];
    }
	for (int i = 0 ; i < [receptionArray count]; i++) {
		NSDictionary* dict = [receptionArray objectAtIndex:i];
        NSString *guideName = [dict objectForKey:@"personShowName"];
		
		UIFont *baseFone     = [UIFont systemFontOfSize:14];
		 size = [guideName sizeWithFont:baseFone constrainedToSize:CGSizeMake(200, 1000) lineBreakMode:UILineBreakModeWordWrap];
		
		UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
		[button setTitle:guideName forState:UIControlStateNormal];
		UIImage *normalImage = [UIImage imageNamed:@"act-normal.png"];
		[button setBackgroundImage:[normalImage stretchableImageWithLeftCapWidth:21 topCapHeight:14] forState:UIControlStateNormal];
		[button setBackgroundImage:[normalImage stretchableImageWithLeftCapWidth:21 topCapHeight:14] forState:UIControlStateHighlighted];
		UIImage *highImage = [UIImage imageNamed:@"act.png"];
		[button setBackgroundImage:[highImage stretchableImageWithLeftCapWidth:21 topCapHeight:14]forState:UIControlStateDisabled];
		
		[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
		[button setTitleColor:[UIColor whiteColor] forState:UIControlStateDisabled];
		button.titleLabel.font = [UIFont systemFontOfSize:14];
		button.tag = BUTTON_TAG_BASE+i;
		[button addTarget:self action:@selector(deleteButton:) forControlEvents:UIControlEventTouchUpInside];
		
		//设置按钮位置
		if (receptionWidth+ size.width+10>= 275) {
			receptionHeight = receptionHeight + size.height+18;
			receptionWidth = 8;
			if (receptionHeight > 10.0f) {
				button.frame = CGRectMake(receptionWidth, receptionHeight, size.width+18, 25);
			}else {
				button.frame = CGRectMake(receptionWidth-52, receptionHeight, size.width+18, 25);
			}
		}else {
			button.frame = CGRectMake(receptionWidth, receptionHeight, size.width+18, 25);
		}
		[receptionView addSubview:button];
        
		receptionWidth += size.width+23;
		
		//设置隐藏的textfield中的值
	}
    receptionTextFiled.frame = CGRectMake(receptionWidth, receptionHeight, 280-receptionWidth, 25);
  
	receptionTextFiled.text = @" ";
    //[self.view resignFirstResponder];

    UIButton* addButton = [[UIButton buttonWithType:UIButtonTypeContactAdd] retain];
    addButton.frame = CGRectMake(290, receptionHeight, 24, 24);
	addButton.tag = 99;
	[receptionView addSubview:addButton];
    [addButton addTarget:self action:@selector(addReceptionView) forControlEvents:UIControlEventTouchUpInside]; 
    [addButton release];
    if (person2Send) {
        //addButton.hidden = YES;
    }
	//定义scrollview高度
    receptionView.frame = CGRectMake(0, 0, 320, 43);
	if (receptionHeight > 45) {
		receptionView.frame = CGRectMake(0, 0, 320, 83);
	}
	receptionView.contentSize = CGSizeMake(320, receptionHeight+size.height+14);
    receptionView.scrollsToTop = NO;
    receptionView.pagingEnabled = NO;
    [receptionTextFiled setHidden:NO];
    
    if (receptionHeight > 45)
    {
        [receptionView setContentOffset:CGPointMake(0.0f, receptionView.contentSize.height - 83)];
    }
    else{
        [receptionView setContentOffset:CGPointMake(0.0f, receptionTextFiled.frame.origin.y-10)];
    }
}
//页面恢复原状，按钮全部去掉
-(void)resumeView{
	receptionView.frame = CGRectMake(0, 0, 320, 43);
	receptionView.contentSize = CGSizeMake(320, 43);
	for(UIView *subview in [receptionView subviews]){
		if([[subview class] isSubclassOfClass:UIButton.class]){
			UIButton *tipsButton = (UIButton *)subview;
			[tipsButton removeFromSuperview];
		}
	}
    
    receptionTextFiled.frame = CGRectMake(76, 0, 230, 43);
    NSMutableString *receiver = [[NSMutableString alloc] init];
    for (int i = 0 ; i < receptionArray.count; i++) {
        NSDictionary* dict =[receptionArray objectAtIndex:i];
		NSString *guideName = [dict objectForKey:@"personShowName"];
        //设置隐藏的textfield中的值
		if (i == receptionArray.count - 1) {
			[receiver appendFormat:@"%@",guideName];
		}else {
			[receiver appendFormat:@"%@,",guideName];
		}
    }
    
    receptionTextFiled.text = receiver;
    [receiver release];
}

-(void)removeSelf:(id)sender{
    isButtonDelete = NO;
    [sender removeFromSuperview];
    for(UIView *subview in [receptionView subviews]){
		if([[subview class] isSubclassOfClass:UIButton.class]){
			UIButton *tipsButton = (UIButton *)subview;
			if (tipsButton.tag != 99) {
				[tipsButton setEnabled:YES];
			}
		}
	}
    [receptionTextFiled setHidden:NO];
    receptionTextFiled.text = @" ";
}
-(void)deleteButton:(id)sender{
	isButtonDelete = YES;
	
	UIButton *button = (UIButton *)sender;
	//当选中当前按钮时，其他按钮恢复原状，可以点击
	for(UIView *subview in [receptionView subviews]){
		if([[subview class] isSubclassOfClass:UIButton.class]){
			UIButton *tipsButton = (UIButton *)subview;
			if (tipsButton.tag != 99) {
				[tipsButton setEnabled:YES];
			}
		}
	}
	//当前按钮进入选中状态而且不可点击
	[button setEnabled:NO];
    
    UIButton* textfiled = [[UIButton alloc] initWithFrame:receptionTextFiled.frame];
    textfiled.tag = 90;
    [textfiled addTarget:self action:@selector(removeSelf:) forControlEvents:UIControlEventTouchUpInside];
    [receptionTextFiled setHidden:YES];
    receptionTextFiled.text = @" ";
    [receptionView addSubview:textfiled];
    [textfiled release];
	//删除替补数组中的信息
    
//	for (int i = 0 ; i < self.receptionArray.count; i++) {
//		if (button.tag == BUTTON_TAG_BASE+i) {
//			[self.receptionArray removeObject:[self.receptionArray objectAtIndex:i]];
//            [[MyClass getInstance].personMarkList removeObjectAtIndex:i];
//		}
//	}
}

#pragma mark keyboard响应函数
-(void) keyboardWillShow:(NSNotification*)note{
    //get keyboard size and location
    CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    //nees to translate the bounds to account for rotation.
    keyboardBounds = [self.view convertRect:keyboardBounds toView:nil];
    
    //get a rect for the textView frame
    CGRect containerFrame = containerView.frame;
    if (person2Send) 
        containerFrame.origin.y = self.view.bounds.size.height - (keyboardBounds.size.height + containerFrame.size.height);
    else if(subSend) {
       containerFrame.origin.y = self.view.bounds.size.height - (keyboardBounds.size.height + containerFrame.size.height); 
    }
    else {
        containerFrame.origin.y = self.view.bounds.size.height - (keyboardBounds.size.height + containerFrame.size.height) + self.tabBarController.tabBar.frame.size.height;
    }
    //containerFrame.origin.y = self.view.bounds.size.height - (keyboardBounds.size.height + containerFrame.size.height);

    //table view
    //UITableView *tableView = (UITableView *)[self.view viewWithTag:TABLEVIEWTAG];
    
    //animations settings
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
    
    //set views with new info
    containerView.frame = containerFrame;
    
    //tableView.frame = CGRectMake(0.0f, 0.0f, 320.0f, containerFrame.origin.y);
    //commit animations
    [UIView commitAnimations];
    
}

-(void) keyboardWillHide:(NSNotification*)note{
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    //get a rect for the textView frame
    CGRect containerFrame = containerView.frame;
    containerFrame.origin.y = self.view.bounds.size.height - containerFrame.size.height;
    
    //tableView
   // UITableView *tableView = (UITableView *)[self.view viewWithTag:TABLEVIEWTAG];
	
    
    //animations settings
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationCurve:[curve intValue]];
    [UIView setAnimationDuration:[duration doubleValue]];
    
    //set view with new info
    containerView.frame = containerFrame;
    
    //tableView.frame = CGRectMake(0.0f, 0.0f, 320.0f, containerFrame.origin.y);
    
    //commit animations
    [UIView commitAnimations];
}

#pragma mark HPGrowingTextView delegate
- (void)growingTextView:(HPGrowingTextView *)growingTextView willChangeHeight:(float)height
{
    float diff = (growingTextView.frame.size.height - height);
    
	CGRect r = containerView.frame;
    r.size.height -= diff;
    r.origin.y += diff;
	containerView.frame = r;
}
- (BOOL)growingTextViewShouldBeginEditing:(HPGrowingTextView *)growingTextView{
    [self addOneReception];
	[receptionTextFiled setHidden:NO];
	[self resumeView];
	return YES;
}

#pragma mark UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    //切换textfield的状态
	if (textField == receptionTextFiled) {
        isButtonDelete = NO;
		[receptionTextFiled setHidden:NO];
		[self addReceiver];
	}
	return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
	NSString* candidateString = [textField.text stringByReplacingCharactersInRange:range withString:string]; 
    if ([candidateString length]>[receptionTextFiled.text length]) {
        return NO;
    }else if([receptionTextFiled.text length]==1 ){
        //如果是选中状态则删除对应按钮，不然就将最后一个联系人设为选中状态
        if (isButtonDelete) {
            
            for(UIView *subview in [receptionView subviews]){
                if([[subview class] isSubclassOfClass:UIButton.class]){
                    UIButton *tipsButton = (UIButton *)subview;
                    if (tipsButton.isEnabled == NO) {
                        /*
                        AddressBookContactSearchResult* delContactInfo = [receptionArray objectAtIndex:(tipsButton.tag - BUTTON_TAG_BASE)]; 
                        NSString* key = [NSString stringWithFormat:@"%c",[[delContactInfo.pinyin uppercaseString] characterAtIndex:0]];
                        NSArray* tempArray = [allContactDic objectForKey:key];
                         */
                       
                        
                        [receptionArray removeObjectAtIndex:(tipsButton.tag - BUTTON_TAG_BASE)];
                        [[MyClass getInstance].personMarkList removeObjectAtIndex:(tipsButton.tag - BUTTON_TAG_BASE)];
                        break;
                    }
                }
            }
            
            [self addReceiver];
            
            isButtonDelete = NO;
        }else {
            //将scrollview子视图里面联系人的按钮存放在新的数组里
            NSMutableArray *tempArray = [[NSMutableArray alloc] init];
            for(UIView *subview in [receptionView subviews]){
                if([[subview class] isSubclassOfClass:UIButton.class]){
                    UIButton *tipsButton = (UIButton *)subview;
                    if(tipsButton.tag!=99){
                        [tempArray addObject:tipsButton];
                    }
                }
            }
            if ([[receptionView subviews] count]!=1) {
                for(UIButton *button in tempArray){
                    if (button == [tempArray lastObject]) {
                        [self deleteButton:button];
                    }
                }
            }
            [tempArray removeAllObjects];
            [tempArray release];
        }
        return NO;
    }
    return YES;
}


//add by jzy
-(void)delayPopView{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)delayPopToRootView{
    [self.navigationController popToRootViewControllerAnimated:YES];
}
@end
